package com.briup.upload.service.impl;

import com.briup.common.exception.CustomerException;
import com.briup.common.web.MessageStatus;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.briup.upload.constants.UploadConstants.UPLOAD_BASE_PATH;
/**
 * FastDFS上传工具类
 */
public class FastDFSUploadRemoteServiceImpl{
    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    public List<String> uploadRemoteFile(MultipartFile[] files,String args) throws CustomerException {

        //上传后得到的文件地址
        List<String> list = new ArrayList<>();

        if (Objects.isNull(files) || files.length==0){
            throw new CustomerException(MessageStatus.PARAM_IS_BLANK);
        }
        //循环获取files数组中的文件
        Arrays.stream(files).forEach(file -> {
            list.add(uploadFile(file));
        });

        return list;
    }

    private String uploadFile(MultipartFile file) {
        try {
            if (file.isEmpty()){
                throw new CustomerException(MessageStatus.UPLOAD_FILE_EMPTY);
            }
            StorePath storePath = storageClient.uploadFile("group1",file.getInputStream(),file.getSize(),getSuffix(file));
            return UPLOAD_BASE_PATH + storePath.getFullPath();
        } catch (IOException e) {
            throw new CustomerException(MessageStatus.UPLOAD_FILE_ERROR);
        }
    }




    private void isImage(MultipartFile file) {
        try{
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if(bi == null){
                throw new CustomerException(MessageStatus.UPLOAD_IMAGE_NO);
            }
        }catch (IOException e){
            throw  new CustomerException(MessageStatus.UPLOAD_FILE_ERROR);
        }
    }

    private String getSuffix(MultipartFile file) throws CustomerException {
        String filename = file.getOriginalFilename();
        return Objects.requireNonNull(filename).substring(filename.lastIndexOf(".")+1);
    }

}
